﻿using My.Core.CustomException;
using My.Core.JobTasks;
using Quartz.Impl.Triggers;
using Quartz.Impl;
using Quartz;
using SqlSugar.IOC;
using My.Core.DynamicProxy;
using My.Core.Extensions;
using My.Core.Quartz.Server.IServer;

namespace My.Admin.Tasks.TaskScheduler
{
    public class Job_SqlExecute : JobBase, IJob, IScopedAutoInject
	{
		private readonly ISysTasksQzService tasksQzService;
		private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

		public Job_SqlExecute(ISysTasksQzService tasksQzService)
		{
			this.tasksQzService = tasksQzService;
		}
		public async Task Execute(IJobExecutionContext context)
		{
			await ExecuteJob(context, async () => await Run(context));
		}
		public async Task Run(IJobExecutionContext context)
		{
			AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;

			var info = await tasksQzService.GetByIdAsync(trigger.JobName);

			if (info != null && info.SqlText.IsNotEmpty())
			{
				var result = DbScoped.SugarScope.Ado.ExecuteCommandWithGo(info.SqlText);
				logger.Info($"任务【{info.Name}】sql请求执行结果=" + result);
			}
			else
			{
				throw new CustomException($"任务{trigger?.JobName}执行失败，任务不存在");
			}
		}
	}
}
